var fs = require('fs')
var path = require('path')
const router = require("koa-router")();
const PagerHelper = require("../utils/PagerHelper");
var sourceMap = require('source-map');

router.prefix("/log");

router.get("/", function (ctx, next) {
    ctx.body = "请指明调用方法log";
});

router.get("/json", function (ctx, next) {
    var data = fs.readFileSync(path.join(__dirname, '../log/err.json'))
    ctx.body = JSON.parse(data)
});

function fixPath(filepath) {
    return filepath.replace(/\.[\.\/]+/g, "");
}

var sourcesPathMap = {};

router.get("/source_map_do", function (ctx, next) {
    var data = fs.readFileSync(path.join(__dirname, '../public/html2/01.js.map'));

    var { line, column } = ctx.request;
    var fileContent = data.toString(),
        fileObj = JSON.parse(fileContent),
        sources = fileObj.sources;
        
    sources.map(item => {
        sourcesPathMap[fixPath(item)] = item;
    });

    var consumer = new sourceMap.SourceMapConsumer(fileObj);

    var lookup = {
        line: 1,
        column: 553
    };
    
    var result = consumer.originalPositionFor(lookup);

    var originSource = sourcesPathMap[result.source],
        sourcesContent = fileObj.sourcesContent[sources.indexOf(originSource)];

    result.sourcesContent = sourcesContent;

    ctx.body = result

});


// router.get("/clear", function (ctx, next) {

//     fs.unlinkSync(path.join(__dirname, '../log/err.json'));

//     var obj = {
//         arr: []
//     }

//     fs.writeFileSync(path.join(__dirname, '../log/err.json'), JSON.stringify(obj, null, '\t'));
//     ctx.body = "清空成功"
// });

router.post("/up_http", async (ctx, next) => {

    ctx.body = PagerHelper.SuccessRes();
    return;

    var reqBody = ctx.request.body
    console.log(ctx.request.body)

    // var { logType, javaScriptErrorInfo } = reqBody;

    var data = fs.readFileSync(path.join(__dirname, '../log/err.json'))
    const errJson = JSON.parse(data)



    errJson.arr.unshift(reqBody)



    fs.writeFileSync(path.join(__dirname, '../log/err.json'), JSON.stringify(errJson, null, '\t'), function () {
        console.log("写入成功")
    });


    ctx.body = PagerHelper.SuccessRes();
});

router.post("/up", async (ctx, next) => {

    var reqBody = ctx.request.body
    console.log(ctx.request.body)

    // var { logType, javaScriptErrorInfo } = reqBody;

    var data = fs.readFileSync(path.join(__dirname, '../log/err.json'))
    const errJson = JSON.parse(data)

    // errJson.arr.push({
    //     logType,
    //     javaScriptErrorInfo
    // })

    errJson.arr.unshift(reqBody)



    fs.writeFileSync(path.join(__dirname, '../log/err.json'), JSON.stringify(errJson, null, '\t'), function () {
        console.log("写入成功")
    });


    ctx.body = PagerHelper.SuccessRes();
});

module.exports = router;
